<template>
  <div class="search">
    <!-- 导航栏 -->
    <van-nav-bar
      title="搜索"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />

    <!-- 搜索框 -->
    <div class="inputbox">
      <form action="/">
        <van-search
          v-model="value"
          show-action
          placeholder="输入商品名称关键字"
          @input="search"
          @cancel="onCancel"
          shape="round"
        />
      </form>

      <!-- 历史搜索、热门推荐 -->
      <div v-if="products.length === 0 || value === ''">
        <div v-show="keywords.length === 0 ? false : true">
          <div class="searchbox">
            <div class="title">历史搜索</div>
            <div class="del" @click="clearAll">
              清除
              <van-icon name="delete-o" />
            </div>
          </div>
          <div class="recommend">
            <div
              class="recommendbox"
              v-for="(item, index) in keywords"
              :key="index"
            >
              {{ item.title }}
              <van-icon name="cross" @click="removeOne(index)" />
            </div>
          </div>
        </div>

        <div class="searchbox">
          <div class="title">热门推荐</div>
        </div>
        <div class="recommend">
          <div
            class="recommendbox"
            v-for="(item, index) in productData"
            :key="index"
            @click="viewProductDetail($event, item.pid)"
          >
            {{ item.name }}
          </div>
        </div>
      </div>

      <!-- 搜索弹出商品列表 -->
      <div v-else>
        <div class="products">
          <div
            class="productsbox"
            v-for="(item, index) in products"
            :key="index"
            @click="viewProductDetail($event, item.pid)"
          >
            <!-- 图片 -->
            <div class="img">
              <img :src="item.smallImg" alt="" />
            </div>

            <!-- 名字 -->
            <div class="name">{{ item.name }}</div>

            <!-- 价格 -->
            <div class="price">&yen; {{ item.price }}</div>
          </div>
        </div>
      </div>

      <van-overlay :show="show" @click="show = false">
        <!-- 商品详情页 -->
        <div class="wrapper">
          <div class="block" @click.stop>
            <!-- 关闭页面 -->
            <div class="btn" @click="show = false"></div>
            <!-- 商品详情插槽页面 -->
            <Product :arr="arr"></Product>
          </div>
        </div>
      </van-overlay>
    </div>
  </div>
</template>

<script>
import Product from "../components/Product.vue";
export default {
  name: "Search",

  //插槽
  components: {
    Product,
  },

  data() {
    return {
      value: "",
      arr: "",
      show: false,

      //推荐商品数据
      productData: [],

      //商品数据
      products: [],

      //定时器序号
      timer: null,

      //所有搜索过的关键字, 最多10个
      keywords: [],
    };
  },

  created() {
    this.getProductData();

    //获取搜索历史记录
    let historySearch = localStorage.getItem("historySearch");
    
    if (historySearch) {
      this.keywords.push(...JSON.parse(historySearch));
    }
  },

  methods: {
    //返回
    onClickLeft() {
      this.$router.push({ name: "Order" });
    },

    //取消搜索
    onCancel() {
      this.products = [];
    },

    //获取热门推荐数据
    getProductData() {
      //发起请求
      this.axios({
        method: "get",
        url: "/typeProducts",
        params: {
          key: "isHot",
          value: 1,
        },
      })
        .then((res) => {
          //   

          if (res.data.code === 500) {
            this.productData = res.data.result;
          }

          //   
        })
        .catch((err) => {
          
        });
    },

    //输入关键字搜索
    search() {
      //使用函数节流控制触发函数执行的频率
      clearTimeout(this.timer);

      this.timer = setTimeout(() => {
        // 

        //获取输入商品名称关键字
        this.searchProduct();
        // 

        if (this.value.trim() === "") {
          return;
        }

        this.axios({
          method: "get",
          url: "/search",
          params: {
            name: this.value,
          },
        })
          .then((res) => {
            // 

            if (res.data.code === "Q001") {
              this.products = res.data.result;
            }
            // 
          })
          .catch((err) => {
            
          }, 1000);
      });
    },

    //搜索记录
    searchProduct() {
      if (this.value.trim() === "") {
        return;
      }

      this.axios({
        method: "get",
        url: "/search",
        params: {
          name: this.value,
        },
      })
        .then((res) => {
          
          if (res.data.code === "Q001") {
            this.products = res.data.result;

            if (res.data.result.length > 0) {
              //验证是否存在重复的关键字
              for (let i = 0; i < this.keywords.length; i++) {
                if (this.keywords[i].title === this.value) {
                  return;
                }
              }

              //是否搜索关键字超出10个, 则移除第一个关键字
              if (this.keywords.length === 10) {
                this.keywords.splice(0, 1);
              }

              this.keywords.push({ title: this.value });
              localStorage.setItem(
                "historySearch",
                JSON.stringify(this.keywords)
              );

            //   
            }
          }
        })
        .catch((err) => {
          
        });
    },

    //单个删除关键字
    removeOne(index) {
      
      this.keywords.splice(index, 1);
      localStorage.setItem("historySearch", JSON.stringify(this.keywords));
    },

    //删除所有搜索关键字
    clearAll() {
      //清空数组
      this.keywords = [];
      localStorage.setItem("historySearch", JSON.stringify(this.keywords));
    },

    //查看商品详情
    viewProductDetail(event, pid) {
      this.show = true;
      this.arr = pid;
      // 
    },
  },
};
</script>

<style lang="less" scoped>
// 导航栏
/deep/.van-nav-bar {
  position: fixed;
  width: 100%;
  top: 0;
  height: 40px;
}

/deep/.van-nav-bar__title {
  color: #37343b;
  font-weight: 600;
}

/deep/.van-nav-bar__text {
  color: #37343b;
  font-weight: 600;
}

/deep/.van-nav-bar .van-icon {
  color: #37343b;
}

//搜索框
.inputbox {
  width: 100%;
  position: absolute;
  top: 40px;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
}

/deep/.van-search__content--round {
  background-color: #f3f3f3;
}

/deep/.van-search__action {
  color: #37343b;
  font-weight: 600;
}

// 历史搜索、热门推荐
.searchbox {
  width: 100%;
  display: flex;
}

.title {
  width: 80px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  color: #37343b;
  font-size: 14px;
  font-weight: 600;
}

.del {
  width: 60px;
  font-size: 12px;
  text-align: center;
  color: #999;
  margin-left: auto;
}

.recommend {
  width: 200px;
  margin-right: auto;
  display: flex;
  flex-wrap: wrap;
  padding: 6px 10px;
}

.recommendbox {
  height: 20px;
  line-height: 20px;
  border-radius: 10px;
  background-color: #f3f3f3;
  text-align: center;
  padding: 4px 10px;
  margin-bottom: 10px;
  color: #999;
  &:nth-child(2n) {
    margin-left: 10px;
  }
  &:nth-child(3n) {
    margin-left: 10px;
  }
}

// 搜索弹出商品列表
.products {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
}

.productsbox {
  width: 100%;
  background-color: #f3f3f3;
  padding: 4px 14px;
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.img {
  width: 50px;
  height: 50px;
}

.img img {
  width: 50px;
  height: 50px;
}

.name {
  width: 100px;
  text-align: left;
  padding: 0 20px;
}

.price {
  width: 60px;
  text-align: right;
  margin-left: auto;
}

// 商品详情页
.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  position: fixed;
  left: 26px;
  bottom: 80px;
}

.block {
  width: 320px;
  height: 520px;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  overflow-y: auto;
  overflow-x: hidden;
  background-color: #fff;
}

.btn {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  text-align: center;
  background-image: url("../assets/nav/close.svg");
  background-size: cover;
  position: relative;
  top: 6px;
  right: 6px;
  margin-left: auto;
}
</style>